package top.anydata.lifeofcode.lifesystem.conf;

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import top.anydata.lifeofcode.lifesystem.entity.sys.user.SysAuthUserEntity;
import top.anydata.lifeofcode.lifesystem.service.sys.user.IUserService;

import java.io.Serializable;

/**
 * 功能描述:
 *
 * @author <a href="mailto:caingao@anydata.top">CainGao</a>
 * @version V_1.0
 * @date 2024/4/9 9:48 AM
 */
@Slf4j
@AllArgsConstructor
@Component
public class CustomPermissionEvaluator implements PermissionEvaluator {

    @Autowired
    private IUserService userService;

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        log.info("hasPermission,authentication:{},targetDomainObject:{},permission:{}", authentication, targetDomainObject, permission);
        if (authentication == null || !(permission instanceof String)) {
            return false;
        }
        String userName = authentication.getName();
        log.info(userName, authentication.getPrincipal());
        SysAuthUserEntity user = (SysAuthUserEntity) authentication.getPrincipal();
        return user.getRoles().stream().flatMap(role->role.getPermissions().stream()).anyMatch(permiss->permiss.getPath().equalsIgnoreCase((String) permission));
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        throw new UnsupportedOperationException("hasPermission not support id");
    }
}
